#!/usr/bin/python
# -*- coding:utf-8 -*-

import codecs
import traceback
import xml.dom.minidom as minidom

def covert_to_unicode(msg):
        '''将转入的编码转换为unicode，只接受ISO-8859-1和unicode编码'''
        __re_str = None
        if isinstance(msg, unicode):
            __re_str = msg
        elif isinstance(msg, str):
            try:
                __re_str = msg.decode('ISO-8859-1')
            except Exception, errinfo:
                raise Exception, '%s,%s' % (errinfo, str(msg))
        else:
            raise Exception, '%s 必须为str或unicode类型' % msg
        return __re_str
    
class CreateCovXml():
    
    def __init__(self, cov_xml_path):
        self.__cov_path = cov_xml_path
        self.__dom = None
        self.__root = None
        self.__shipment = None
        self.__receiver = None
        self.__cn23 = None

    def _covert_code(self, msg):
        return covert_to_unicode(msg)
    
    def __create_new_node(self, node_name, node_text=None):
        '''为xml文件添加一个结点,其中node_text可以为空'''        
        if self.__dom == None:
            raise Exception, '创建结点时，document对象还不存在'
        # 创建的是结点只有结点名
        if None == node_text:
            return self.__dom.createElement(self._covert_code(node_name))
        else:
            newNode = self.__dom.createElement(self._covert_code(node_name))
            newText = self.__dom.createTextNode(self._covert_code(node_text))
            newNode.appendChild(newText)
            return newNode
            
    def begin_cov(self, orderno):
        '''begin_cov(self) --> None 创建coverage.xml文档和根结点'''
        try:
            impl = minidom.getDOMImplementation()
            self.__dom = impl.createDocument(None, u'pacsoft', None)
            self.__root = self.__dom.documentElement
            new_receiver_node = self.__create_new_node("receiver")
            new_receiver_node.setAttribute('rcvid', 'SE')  # 这里填接收人的编号，这里没有
            new_shipment_node = self.__create_new_node("shipment")
            new_shipment_node.setAttribute('orderno', orderno)
            self.__receiver = new_receiver_node
            self.__shipment = new_shipment_node
            self.__cn23 = self.__create_new_node("cn23")
            self.__shipment.appendChild(self.__cn23)
            self.__root.appendChild(new_receiver_node)
            self.__root.appendChild(new_shipment_node)
        except:
            traceback.print_exc()
            raise Exception, '创建coverage xml根结点失败'
        
    def add_goods(self, goods):
        statno = "19011010"
        if len(goods) > 5:
            statno = str(goods[5])
        new_line_node = self.__create_new_node("line")
        new_statno_node = self.__create_new_node("val", statno)  # 海关号后面重新要拿过
        new_statno_node.setAttribute('n', 'statno')
        new_quantity_node = self.__create_new_node("val", str(goods[3]))
        new_quantity_node.setAttribute('n', 'quantity')
        new_netweight_node = self.__create_new_node("val", str(goods[2]))
        new_netweight_node.setAttribute('n', 'netweight')
        new_customsvalue_node = self.__create_new_node("val", str(goods[4]))
        new_customsvalue_node.setAttribute('n', 'customsvalue')
        new_contents_node = self.__create_new_node("val", goods[1])
        new_contents_node.setAttribute('n', 'contents')
        new_line_node.appendChild(new_statno_node)
        new_line_node.appendChild(new_quantity_node)
        new_line_node.appendChild(new_netweight_node)
        new_line_node.appendChild(new_customsvalue_node)
        new_line_node.appendChild(new_contents_node)
        self.__cn23.appendChild(new_line_node)

    def add_weight(self, weight):
        new_container_node = self.__create_new_node("container")
        new_container_node.setAttribute("type", "parcel")
        new_weight_node = self.__create_new_node("val", weight)
        new_weight_node.setAttribute("n", "weight")
        new_container_node.appendChild(new_weight_node)
        self.__shipment.appendChild(new_container_node)

    
    def creat_shipment(self, reference="DE office"):
        new_from_node = self.__create_new_node("val", "1")
        new_from_node.setAttribute("n", "from")
        new_to_node = self.__create_new_node("val", "SE")  # 不知道数据怎么来
        new_to_node.setAttribute("n", "to")
        new_reference_node = self.__create_new_node("val", reference)  # 不知道数据怎么来
        new_reference_node.setAttribute("n", "reference")
        new_termcode_node = self.__create_new_node("val")
        new_termcode_node.setAttribute("n", "termcode")
        new_service_node = self.__create_new_node("service")
        new_service_node.setAttribute("srvid", "PDK340")  # 不知道数据怎么来
        new_addon_node = self.__create_new_node("addon")
        new_addon_node.setAttribute("adnid", "NOTEMAIL")
        new_service_node.appendChild(new_addon_node)

        # ufonline
        new_ufonline_node = self.__create_new_node("ufonline")
        new_option_node = self.__create_new_node("option")
        new_option_node.setAttribute('optid', "LNKPRTN")
        line_from_email_node = self.__create_new_node("val", "info@greenmyday.dk")
        line_from_email_node.setAttribute('n', 'from')
        line_to_email_node = self.__create_new_node("val", "guomodi@greenmyday.dk")
        line_to_email_node.setAttribute('n', 'to')
        new_option_node.appendChild(line_from_email_node)
        new_option_node.appendChild(line_to_email_node)
        new_ufonline_node.appendChild(new_option_node)
        
        self.__shipment.appendChild(new_from_node)
        self.__shipment.appendChild(new_to_node)
        self.__shipment.appendChild(new_reference_node)
        self.__shipment.appendChild(new_termcode_node)
        self.__shipment.appendChild(new_service_node)
        
        self.__shipment.appendChild(new_ufonline_node)
    def create_receiver(self, receiver):
        # 0 id 1 consignee 2 address 3 district 4 city 5 province 6 coutry 7 zipcode 8 tel 9 mobile 10 email 11 shipping_name 12 postscript
        line_name_node = self.__create_new_node("val", receiver[1])
        line_name_node.setAttribute('n', 'name')
        line_address1_node = self.__create_new_node("val", ",".join(receiver[2:6]))
        line_address1_node.setAttribute('n', 'address1')
        line_zipcode_node = self.__create_new_node("val", receiver[7])
        line_zipcode_node.setAttribute('n', 'zipcode')
        line_city_node = self.__create_new_node("val", receiver[3])
        line_city_node.setAttribute('n', 'city')
        line_country_node = self.__create_new_node("val", receiver[6])
        line_country_node.setAttribute('n', 'country')
        phone = receiver[8]
        if phone == '':
            phone = receiver[9]
        line_phone_node = self.__create_new_node("val", phone)
        line_phone_node.setAttribute('n', 'phone')
        line_contact_node = self.__create_new_node("val", receiver[1])
        line_contact_node.setAttribute('n', 'contact')
        new_receiver_node = self.__receiver
        
        new_receiver_node.appendChild(line_name_node)
        new_receiver_node.appendChild(line_address1_node)
        new_receiver_node.appendChild(line_zipcode_node)
        new_receiver_node.appendChild(line_city_node)
        new_receiver_node.appendChild(line_country_node)
        new_receiver_node.appendChild(line_phone_node)
        new_receiver_node.appendChild(line_contact_node)

    def end_cov(self):
        try:
            f = open(self.__cov_path, 'wb')
            writer = codecs.lookup('utf-8')[3](f)
            self.__dom.writexml(writer, encoding='utf-8')  
            writer.close()
            f.close()
            return True
        except Exception, err:
            traceback.print_exc() 
            raise Exception, '写coverage.xml文件出错'
